package com.molyfun.parents.view;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.SparseArray;
import android.view.ViewGroup;

import com.molyfun.parents.fragment.main.ClassCenterFragment;
import com.molyfun.parents.fragment.main.MineClassRoomFragment;
import com.molyfun.parents.fragment.main.MineCourseFragment;
import com.molyfun.parents.fragment.main.MineMsgFragment;
import com.molyfun.parents.fragment.main.SchoolOnlineFragment;

import java.lang.ref.SoftReference;

/**
 * Created by ZhaoWei on 2016/7/25.
 */
public class MainPagerAdapter extends FragmentPagerAdapter {

    private SparseArray<SoftReference<Fragment>> viewCache = new SparseArray<SoftReference<Fragment>>();


    public MainPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        return super.instantiateItem(container, position);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
    }

    private Fragment getViewByType(int type) {
        switch (type) {
            case 0:
                return new ClassCenterFragment();
            case 1:
                return new SchoolOnlineFragment();
            case 2:
                return new MineCourseFragment();
            case 3:
                return new MineClassRoomFragment();
            case 4:
                return new MineMsgFragment();
            default:
                return null;
        }
    }

    @Override
    public Fragment getItem(int position) {
        SoftReference<Fragment> viewWeakReference = viewCache.get(position);
        Fragment view = null;
        if (viewWeakReference != null && viewWeakReference.get() != null) {
            view = viewWeakReference.get();
        }
        if (view == null) {
            view = getViewByType(position);
            viewCache.put(position, new SoftReference<Fragment>(view));
        }
        return view;
    }

    @Override
    public int getCount() {
        return 5;
    }

    @Override
    public int getItemPosition(Object object) {
        return super.getItemPosition(object);
    }

}
